package dhy.com.exception;

import dhy.com.result.AjaxResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

//针对@ResponseBody标注的方法做统一的返回值处理
@Component
@ControllerAdvice
public class GlobalResponseAdvice implements ResponseBodyAdvice {

  @Override
  public boolean supports(MethodParameter methodParameter, Class aClass) {
    return true;
  }

  @Override
  public Object beforeBodyWrite(Object body,
                                MethodParameter methodParameter,
                                MediaType mediaType,
                                Class aClass,
                                ServerHttpRequest serverHttpRequest,
                                ServerHttpResponse serverHttpResponse) {
    //如果响应结果是JSON数据类型
    if(mediaType.getType().equals(MediaType.APPLICATION_JSON.getType())) {
      //返回的是AjaxResponse
      if (body instanceof AjaxResponse) {
        AjaxResponse ajaxResponse = (AjaxResponse) body;
        //状态码统一
        serverHttpResponse.setStatusCode(HttpStatus.valueOf(
                ajaxResponse.getCode()));
      return body;
    }
      else
      {
        //不是AjaxResponse
        //serverHttpResponse.setStatusCode(HttpStatus.OK);
        return AjaxResponse.success(body);
      }
      }
    return body;
    }
  }

